package org.dromara.patrol.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.patrol.PatrolSnapException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.device.api.RemoteDeviceService;
import org.dromara.patrol.domain.PatrolReport;
import org.dromara.patrol.domain.PatrolSnapImg;
import org.dromara.patrol.domain.PatrolSnapPlan;
import org.dromara.patrol.domain.PatrolSnapRecord;
import org.dromara.patrol.domain.bo.PatrolSnapImgBo;
import org.dromara.patrol.domain.vo.PatrolReportVo;
import org.dromara.patrol.domain.vo.PatrolSnapImgVo;
import org.dromara.patrol.domain.vo.PatrolSnapRecordVo;
import org.dromara.patrol.mapper.PatrolReportMapper;
import org.dromara.patrol.mapper.PatrolSnapImgMapper;
import org.dromara.patrol.mapper.PatrolSnapPlanMapper;
import org.dromara.patrol.mapper.PatrolSnapRecordMapper;
import org.dromara.patrol.service.IPatrolSnapImgService;
import org.dromara.system.api.RemoteStoreService;
import org.dromara.system.api.RemoteUserService;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 巡店管理-抓拍巡店图片Service业务层处理
 *
 * @author LionLi
 * @date 2024-03-27
 */
@RequiredArgsConstructor
@Service
public class PatrolSnapImgServiceImpl implements IPatrolSnapImgService {

    private final PatrolSnapImgMapper baseMapper;

    private final PatrolSnapPlanMapper patrolSnapPlanMapper;

    private final PatrolSnapRecordMapper patrolSnapRecordMapper;





    @DubboReference
    private final RemoteDeviceService remoteDeviceService;

    @DubboReference
    private final RemoteStoreService  remoteStoreService;

    @DubboReference
    private final RemoteUserService remoteUserService;
    /**
     * 查询巡店管理-抓拍巡店图片
     */
    @Override
    public PatrolSnapImgVo queryById(Long imgId){
        return baseMapper.selectVoById(imgId);
    }

    /**
     * 查询巡店管理-抓拍巡店图片列表
     */
    @Override
    public TableDataInfo<PatrolSnapImgVo> queryPageList(PatrolSnapImgBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PatrolSnapImg> lqw = buildQueryWrapper(bo);
        Page<PatrolSnapImgVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollUtil.isEmpty(result.getRecords())) {
            return TableDataInfo.build(result);
        }
        List<Long> deviceId = result.getRecords().stream().map(PatrolSnapImgVo::getDeviceId).distinct().toList();
        Map<Long, String> deviceNameMap = remoteDeviceService.queryNameByDeviceIds(deviceId);

        result.getRecords().forEach(item -> {
            if (ObjUtil.isNotNull(item)
                    && ObjUtil.isNotNull(item.getDeviceId())) {
                item.setDeviceName(deviceNameMap.get(item.getDeviceId()));
            }
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询巡店管理-抓拍巡店图片列表
     */
    @Override
    public List<PatrolSnapImgVo> queryList(PatrolSnapImgBo bo) {
        LambdaQueryWrapper<PatrolSnapImg> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PatrolSnapImg> buildQueryWrapper(PatrolSnapImgBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PatrolSnapImg> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getSnapPlanId() != null, PatrolSnapImg::getSnapPlanId, bo.getSnapPlanId());
//        lqw.eq(bo.getStoreId() != null, PatrolSnapImg::getStoreId, bo.getStoreId());
//        lqw.eq(bo.getDeviceId() != null, PatrolSnapImg::getDeviceId, bo.getDeviceId());
//        lqw.eq(StringUtils.isNotBlank(bo.getChannelIds()), PatrolSnapImg::getChannelIds, bo.getChannelIds());
//        lqw.eq(StringUtils.isNotBlank(bo.getImgUrl()), PatrolSnapImg::getImgUrl, bo.getImgUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getInspectStatus()), PatrolSnapImg::getInspectStatus, bo.getInspectStatus());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
                PatrolSnapImg::getCreateTime, params.get("beginTime"), params.get("endTime"));
        lqw.orderByDesc(PatrolSnapImg::getCreateTime);
        lqw.orderByDesc(PatrolSnapImg::getImgId);


        return lqw;
    }

    /**
     * 新增巡店管理-抓拍巡店图片
     */
    @Override
    public Boolean insertByBo(PatrolSnapImgBo bo) {
        PatrolSnapImg add = MapstructUtils.convert(bo, PatrolSnapImg.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setImgId(add.getImgId());
        }
        return flag;
    }

    /**
     * 修改巡店管理-抓拍巡店图片
     */
    @Override
    public Boolean updateByBo(PatrolSnapImgBo bo) {
        PatrolSnapImg update = MapstructUtils.convert(bo, PatrolSnapImg.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PatrolSnapImg entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除巡店管理-抓拍巡店图片
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 批量插入
     * @param patrolSnapImgList
     * @return
     */
    @Override
    public Boolean insertBatch(List<PatrolSnapImg> patrolSnapImgList) {
        if (baseMapper.insertBatch(patrolSnapImgList)) {
            return true;
        }
        throw new PatrolSnapException("持久化异常");
    }

    /**
     * 图片详情信息
     *
     * @param imgId
     * @return
     */
    @Override
    public R<PatrolSnapImgVo> getImgInfo(Long imgId) {
        PatrolSnapImgVo patrolSnapImgVo = baseMapper.selectVoById(imgId);
        if (ObjUtil.isNull(patrolSnapImgVo)) {
            return R.fail("图片不存在");
        }
        //获取设备的名字
        Map<Long, String> deviceNameMap = remoteDeviceService.queryNameByDeviceIds(Collections.singletonList(patrolSnapImgVo.getDeviceId()));
        patrolSnapImgVo.setDeviceName(deviceNameMap.get(patrolSnapImgVo.getDeviceId()));
        //获取计划的名字
        PatrolSnapPlan patrolSnapPlan = patrolSnapPlanMapper.selectById(patrolSnapImgVo.getSnapPlanId());
        if (ObjUtil.isNotNull(patrolSnapPlan)){
            patrolSnapImgVo.setPlanName(patrolSnapPlan.getPlanName());
        }
        //获取门店的名字
        String name = remoteStoreService.selectNameByStoreId(patrolSnapPlan.getStoreId());
        patrolSnapImgVo.setStoreName(name);
        //获取处理照片集合
        LambdaQueryWrapper<PatrolSnapRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PatrolSnapRecord::getSnapImageId,imgId);
        List<PatrolSnapRecordVo> patrolSnapRecordVos = patrolSnapRecordMapper.selectVoList(wrapper);
        List<Long> userIds = patrolSnapRecordVos.stream().map(PatrolSnapRecordVo::getCreateBy).collect(Collectors.toList());
        Map<Long, String> userNameMap = remoteUserService.selectNickNameByIds(userIds);
        patrolSnapRecordVos.forEach(item -> {
            if (ObjUtil.isNotNull(item)
                    && ObjUtil.isNotNull(item.getCreateBy())) {
                item.setRecordName(userNameMap.get(item.getCreateBy()));
            }
        });
        patrolSnapImgVo.setRecordVos(patrolSnapRecordVos);
        return R.ok(patrolSnapImgVo);
    }
}
